/*
 * Copyright the original author or authors.
 * 
 * Licensed under the MOZILLA PUBLIC LICENSE, Version 1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *	  http://www.mozilla.org/MPL/MPL-1.1.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.milib.tools {
	import com.googlecode.milib.MILibMain;
	import com.googlecode.milib.base.MLBroadcastClass;
	import com.googlecode.milib.dbg.view.content.graph.IMLDBGGraphModel;
	import com.googlecode.milib.dbg.view.content.graph.MLDBGGraphLogData;

	import flash.display.Stage;
	import flash.events.Event;
	import flash.utils.getTimer;

	/**
	 * @author Marek Brun
	 */
	public class MLDBGFPSMonitor extends MLBroadcastClass implements IMLDBGGraphModel {

		public function get event_Updated():String {
			return 'Updated';
		}
		
		private var fpsLog:Array=[];
		private var lastTime:int;		private var countFrames:uint=0;
		private var stage:Stage;		private var frequency:uint=1000;
		
		public function MLDBGFPSMonitor() {
			MILibMain.getInstance().getRoot().addEventListener(Event.ENTER_FRAME, onStageEnterFrame, false, 0, true);
			lastTime=getTimer();
			stage=MILibMain.getInstance().getStage();
		}

		private function doEnterFrame():void {
			countFrames++;
			if(getTimer()-lastTime>frequency) {
				fpsLog.push(new MLDBGGraphLogData(countFrames));//Math.round(countFrames*((getTimer()-lastTime)/frequency)*(1000/frequency))));
				countFrames=0;
				lastTime=getTimer();
				broadcastEvent(event_Updated);
			}
		}
		
		public function getData():Array {
			return fpsLog;
		}
		
		public function getTextData():String {
			return 'FPS: '+getCurrentFPS()+'/'+stage.frameRate;
		}
		
		public function getCurrentFPS():uint {
			return fpsLog[fpsLog.length-1].number;
		}
		
		public function getCurrentGraphLogData():MLDBGGraphLogData {
			return fpsLog[fpsLog.length-1];
		}
		
		public function getMax():Number {
			return stage.frameRate;
		}

//********************************************************************************************
//		events for MLDBGFPSObservator
//********************************************************************************************
		protected function onStageEnterFrame(event:Event):void {
			doEnterFrame();
		}
	}
}
